package com.dstats;

import android.app.Fragment;
import android.app.LoaderManager;
import android.content.CursorLoader;
import android.content.Loader;
import android.database.Cursor;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.GridView;

import com.dstats.data.AppDataContract;
import com.nhaarman.listviewanimations.appearance.simple.SwingLeftInAnimationAdapter;

public class HeroesFragment extends Fragment implements LoaderManager.LoaderCallbacks<Cursor>{

    private GridView gridView;
    private HeroAdapter adapter;

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        getLoaderManager().initLoader(R.id.hero_loader, null, this);
    }

    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.hero_fragment, container, false);
        gridView = (GridView) rootView.findViewById(R.id.gridViewHeroes);
        adapter = new HeroAdapter(getActivity(), null, false);
        final SwingLeftInAnimationAdapter animAdapter = new SwingLeftInAnimationAdapter(
                adapter);
        animAdapter.setAbsListView(gridView);
        gridView.setAdapter(animAdapter);
        return rootView;
    }

    @Override
    public Loader<Cursor> onCreateLoader(int i, Bundle bundle) {
        return new CursorLoader(getActivity(), AppDataContract.AppHeroEntry.CONTENT_URI, new String[]{
                AppDataContract.AppHeroEntry._ID,
                AppDataContract.AppHeroEntry.NAME,
                AppDataContract.AppHeroEntry.LOCALIZED_NAME},
                null, null, null);
    }

    @Override
    public void onLoadFinished(Loader<Cursor> cursorLoader, Cursor cursor) {
        adapter.swapCursor(cursor);
    }

    @Override
    public void onLoaderReset(Loader<Cursor> cursorLoader) {
        adapter.swapCursor(null);
    }
}
